package com.thh.mvcframework.servlet;

import com.thh.mvcframework.annotation.ThhAutowired;
import com.thh.mvcframework.annotation.ThhController;
import com.thh.mvcframework.annotation.ThhRequestMapping;
import com.thh.mvcframework.annotation.ThhService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * @description: 对应mvc DispatcherServlet
 * @author: thh
 * @time: 2020/8/1 10:37
 */
public class ThhDispatcherServlet extends HttpServlet {

    private Properties contextConfig = new Properties();
    private List<String> classNames = new ArrayList<>();
    private Map<String,Object> ioc = new HashMap<>();
    private Map<String,Method>  handleMapping= new HashMap<>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //6.调用
        try {
            doDispatch(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 : Exception Detail"+Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath,"").replaceAll("/+","/");
        if (!this.handleMapping.containsKey(url)){
            resp.getWriter().write("404 NOT FOUND");
            return;
        }
        Map<String,String[]> params = req.getParameterMap();
        Method method = this.handleMapping.get(url);
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());

        method.invoke(ioc.get(beanName),new Object[]{req,resp,params.get("name")[0]});
    }


    @Override
    public void init(ServletConfig config) throws ServletException {



        //1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));


        //2.扫描相关的类
        doScanner(contextConfig.getProperty("scanPackage"));


        //3.实例化相关的类
        doInstance();

        //4.完成依赖注入
        doAutowired();

        //5.初始化HandleMappering
        doInitHandleMapping();

        System.out.println("ThhDispatcherServlet init successful");
    }

    private void doInitHandleMapping() {
        if (ioc.isEmpty()){return;}
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if (!clazz.isAnnotationPresent(ThhController.class)){continue;}
            String baseUrl = "";
            if(clazz.isAnnotationPresent(ThhRequestMapping.class)){
                ThhRequestMapping requestMapping = clazz.getAnnotation(ThhRequestMapping.class);
                baseUrl = requestMapping.value();

            }


            for (Method method : clazz.getMethods()) {
                if(!method.isAnnotationPresent(ThhRequestMapping.class)){continue;}
                ThhRequestMapping requestMapping = method.getAnnotation(ThhRequestMapping.class);
                //采用正则  多个/变成/
                String url = ("/"+baseUrl+"/"+requestMapping.value()).replaceAll("/+","/");
                handleMapping.put(url,method);
                System.out.println("mapped: " + url+"."+method);

            }
        }
    }

    private void doAutowired() {
        if(ioc.isEmpty()){return;}
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(ThhAutowired.class)){continue;}
                ThhAutowired autowired = field.getAnnotation(ThhAutowired.class);
                String beanName = autowired.value().trim();
                if ("".equals(beanName)){
                    beanName = field.getType().getName();
                }
                //开启暴力反射 强吻
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doInstance() {
        if (classNames.isEmpty()){return;}

        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);
                //beanName 默认是类名首字母小写   如果有注解就取注解
                //<bean id="" class="”>
               if(clazz.isAnnotationPresent(ThhController.class)) {
                   String beanName = toLowerFirstCase(clazz.getSimpleName());
                   ioc.put(beanName,clazz.newInstance()) ;
               }else if(clazz.isAnnotationPresent(ThhService.class)){
                   //1.默认的类名首字母小写
                   String beanName = toLowerFirstCase(clazz.getSimpleName());
                   //2.自定义命名
                   ThhService service = (ThhService) clazz.getAnnotation(ThhService.class);
                   if (!"".equals(service.value())){
                       beanName = service.value();
                   }
                   Object instance = clazz.newInstance();
                   ioc.put(beanName,instance) ;
                   //3.接口是不能直接实例化的
                   for (Class<?> i : clazz.getInterfaces()) {
                       if (ioc.containsKey(i.getName())){
                           throw  new Exception("The beanName is exists!");
                       }
                       ioc.put(i.getName(),instance);
                   }

               }else {
                   continue;
               }

            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        String assss = toLowerFirstCase("aSSSS");
        String upper = toUpperFirstCase("aaKKKK");
        System.out.println(assss);
    }
    /**
     * 首字母小写
     * @param simpleName
     * @return
     */
    private static String toLowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0]+=32;
        return String.valueOf(chars);
    }
    /**
     * 首字母大写
     * @param simpleName
     * @return
     */
    private static String toUpperFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0]-=32;
        return String.valueOf(chars);
    }


    private void doScanner(String scanPackage) {

        URL url = this.getClass().getClassLoader().getResource( scanPackage.replaceAll("\\.", "/"));
        File classPath = new File(url.getFile());
        //把包扫描下的class文件的文件名称 加入到list  之后进行反射创建对象
        for (File file : classPath.listFiles()) {
            if (file.isDirectory()){
                //递归查询
                doScanner(scanPackage+"."+file.getName());
            }else {
                if (!file.getName().endsWith(".class")){continue;}
                String className = (scanPackage+"."+file.getName()).replace(".class", "");
                classNames.add(className);
            }
        }
    }


    private void doLoadConfig(String contextConfigLocation) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
